package com.github.prontera.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.prontera.Shift;
import com.github.prontera.StatusCode;
import com.github.prontera.domain.Client;
import com.github.prontera.domain.ClientCoterie;
import com.github.prontera.domain.Coterie;
import com.github.prontera.persistence.ClientCoterieMapper;
import com.github.prontera.persistence.CoterieMapper;
import com.github.prontera.persistence.CrudMapper;

/**
 * 友圈
 */
@Service
public class CoterieService extends CrudServiceImpl<Coterie>{
    
    @Autowired
    private CoterieMapper mapper;
    @Autowired
    private ClientService clientService;
    @Autowired
    private ClientCoterieMapper clientCoterieMapper;
    
  	@Autowired
    public CoterieService(CrudMapper<Coterie> mapper) {
        super(mapper);
    }

	public List<Coterie> findFollowCoterie(Coterie coterie) {
		return mapper.findFollowCoterie(coterie);
	}

	public List<Coterie> findCoterie(Coterie coterie) {
		return mapper.findCoterie(coterie);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public boolean updateViewCount(Long id) {
		return mapper.updateViewCount(id)>0;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public boolean insertCoterie(Coterie coterie,Client client) {
		if(mapper.insert(coterie)<=0){
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"参数错误");
		}
		if(!clientService.updateCount(client)){
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"参数错误");
		}
		return true;
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean insertClientCoterie(Long clientId,Long coterieId,Long followCoterieClientId) {
		ClientCoterie clientCoterie=new ClientCoterie();
		clientCoterie.setClientId(clientId);
		clientCoterie.setCoterieId(coterieId);
		clientCoterie.setFollowCoterieClientId(followCoterieClientId);
		return clientCoterieMapper.insert(clientCoterie)>0;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public boolean removeCoterie(Coterie coterie,Client client) {
		if(mapper.remove(coterie)<=0){
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"参数错误");
		}
		ClientCoterie clientCoterie=new ClientCoterie();
		clientCoterie.setCoterieId(coterie.getId());
		if(clientCoterieMapper.remove(clientCoterie)<=0){
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"参数错误");
		}
		clientService.updateCount(client);
		return true;
	}


}
